import React, { useEffect, useState } from 'react';
import './Course.scss'
import { Button, Space, Table, message } from 'antd';
import axios from 'axios';
import { use } from 'echarts';
import { useNavigate } from 'react-router-dom'

const Course = () => {
    var navigate = useNavigate()

    //在组件中定义一个状态selectedRowKeys，用于存储当前选中的行的key值。
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    //onSelectChange方法，用于更新selectedRowKeys状态，以便在组件中显示当前选中的行。
    const onSelectChange = (selectedRowKeys: any) => {
        setSelectedRowKeys(selectedRowKeys);
    };
    //动态切换大图和列表视图
    const [activeTab, setActiveTab] = useState('introduction')

    //设置表格列表配置
    const columns: any = [
        {
            title: '课程名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '课程老师',
            dataIndex: 'teacher',
            key: 'teacher',
        },
        {
            title: '课程时长',
            dataIndex: 'duration',
            key: 'duration',
        },
        {
            title: '发布时间',
            dataIndex: 'time',
            key: 'time',
        },
        {
            title: '发布人员',
            dataIndex: 'staff',
            key: 'staff',
        },
        {
            title: '阅读情况',
            dataIndex: 'read',
            key: 'read',
        },
        {
            title: '操作',
            key: 'name',
            render: (a: any, record: any, index: any) => {
                return (
                    <>
                        <Button type='primary' danger onClick={() => viewclick(record)}>查看</Button>,
                        <Button type='primary' danger onClick={() => editcilck(record)}>编辑</Button>,
                    </>
                )
            }
        }
    ]
    //数据源
    var [data, setData] = useState([])

    //等待数据状态
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        datalist()
    }, [])
    var datalist = async () => {
        var res = await axios({
            url: "http://localhost:3000/course"
        })
        //给数据的每一项添加一个key,方便对每一项数据进行操作
        var numlist = res.data.map((item: any) => ({
            ...item,
            key: item.id
        }))
        setData(numlist)
        setLoading(false); //数据加载完成，将loading状态设为false
    }
    // 新增课程
    var handleClick = () => {
        navigate('/index/courseadd')
    }
    //在rowSelection对象中添加selectedRowKeys属性，将其值设为selectedRowKeys状态，用于控制Table表格中选中的行
    const rowSelection: any = {
        selectedRowKeys,
        onChange: onSelectChange,
    };
    //删除按钮
    var handleDeleteSelected = () => {
        const selectedKeys = selectedRowKeys;
        console.log(selectedKeys);
        if (selectedRowKeys.length === 0) {
            message.warning('请先选择要删除的行');
            return;
        }
        if (selectedRowKeys.length === 1) {
            //等于1就是单个删除
            axios({
                url: `http://localhost:3000/course/${selectedKeys}`,
                method: "delete"
            }).then(res => {
                // console.log("删除成功");
                message.success('删除成功');
                datalist()
            }).catch(error => {
                // console.log("失败");
                message.error('删除失败');
            })
        } else {
            // 如果选中行的数量大于1，执行全部删除操作
            axios({
                url: 'http://localhost:3000/course',
                method: 'DELETE',
                data: selectedRowKeys,
                // headers: {
                //     'Content-Type': 'application/json',
                // },
            }).then(res => {
                // console.log("删除成功");
                message.success('删除成功');
                datalist()
            }).catch(error => {
                // console.log("失败");
                message.error('删除失败');
            })
        }
    }
    //编辑按钮
    var editcilck = (record: any) => {
        console.log(record);
        navigate('/index/courseadd', { state: { record } })
    }
    //查看
    var viewclick = (record: any) => {
        // console.log(record);
        navigate(`/index/coursejs`, { state: { record } }) //将record作为状态对象传递到页面中
    }

    return (
        <div className='course'>
            <div className='header'>
                <div>所有课程</div>
                <div>首页{'>'}所有课程</div>
            </div>
            <div className='btn'>
                <div className='leftbtn'>
                    <Button type="primary" onClick={handleDeleteSelected}>删除选择</Button>
                    <Button type="primary" className={activeTab === 'introduction' ? 'tab active' : 'tab'} onClick={() => setActiveTab('introduction')} >列表模式</Button>
                    <Button type="primary" className={activeTab === 'checkin' ? 'tab active' : 'tab'} onClick={() => setActiveTab('checkin')} >大图模式</Button>
                </div>
                <div className='rightbtn'>
                    <Button type="primary">导出</Button>
                    <Button type="primary" onClick={handleClick}>新增课程</Button>
                </div>
            </div>
            <div>
                {activeTab === 'introduction' ?
                    <div>
                        <Table columns={columns} dataSource={data} rowSelection={rowSelection} />
                    </div> :
                    <div className='bottom'>
                        {loading ?
                            <div>Loading...</div> :
                            <div className='bottom-item'>
                                {data.map((item: any) => (
                                    <div key={item.key} className='dataitem'>
                                        <img src={item.img} alt="" />
                                        <div className='one'>
                                            {item.name}
                                            <div>{item.time}</div>
                                        </div>
                                        <div className='one'>
                                            开课时间
                                            <div>{item.time}</div>
                                        </div>
                                        <div className='one'>
                                            课程时长
                                            <div>{item.chixu}</div>
                                        </div>
                                        <div className='one'>
                                            课程老师
                                            <div>{item.teacher}</div>
                                        </div>
                                        <div className='one'>
                                            已读数量
                                            <div>{item.read}</div>
                                        </div>
                                        <div className='btn'>
                                            <Button className='btn1'  danger onClick={() => viewclick(item)}>查看</Button>,
                                            <Button className='btn2'  danger onClick={() => editcilck(item)}>编辑</Button>,
                                        </div>
                                    </div>
                                ))}
                            </div>
                        }
                    </div>
                }
            </div>
            <div></div>
        </div>
    );
};

export default Course;